package com.yuanduan.mplus.view;

import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v7.widget.Toolbar;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.MaterialDialog;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.target.ViewTarget;
import com.cj.framework.app.BaseActivity;
import com.cj.framework.app.BaseApplication;
import com.cj.framework.util.FileUtils;
import com.cj.framework.util.IOkHttp;
import com.cj.framework.util.Msg;
import com.cj.framework.util.OkHttpImp;
import com.cj.framework.widget.CircleImageView;
import com.yuanduan.mplus.R;
import com.yuanduan.mplus.config.Config;
import com.yuanduan.mplus.db.dao.UserDao;
import com.yuanduan.mplus.db.entity.User;
import com.yuanduan.mplus.model.entity.RS;
import com.yuanduan.mplus.model.entity.RSIdentity;
import com.yuanduan.mplus.util.FileImageUpload;

import java.io.File;
import java.util.HashMap;
import java.util.List;

/**
 * 个人设置界面
 */
public class PersonalSetting extends BaseActivity implements View.OnClickListener {
    private Toolbar toolbar;
    private RelativeLayout rl_head;
    private CircleImageView ci_head;
    private RelativeLayout rl_name;
    private TextView tv_name;
    private TextView tv_phone;
    private RelativeLayout rl_sex;
    private TextView tv_sex;
    private RelativeLayout rl_age;
    private TextView tv_age;
    private RelativeLayout rl_job;
    private TextView tv_job;
    private RelativeLayout rl_insure;
    private TextView tv_owner;

    public static final String TYPE_HEAD="COM.CJ.HEADUPDATE";
    public static final String TYPE_NAME="COM.CJ.NAMEUPDATE";
    private static final int CAPTURE_IMAGE=110;
    private static final int GALLERY_IAMGE=111;
    public static String url_front;
    public static String url_back;
    public static String num_identity;
    private User user;

    private String temp_name;
    private String temp_sex;
    private String temp_job;

    private ProgressDialog dialog;
    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 0://图片上传失败
                    Toast.makeText(PersonalSetting.this,"上传失败",Toast.LENGTH_SHORT).show();
                    break;
                case 1://图片上传成功
                    dealwithUploadSuccess();
                    break;
            }
        }
    };
    private FileImageUpload.ImageCallback imageCallback=new FileImageUpload.ImageCallback() {
        @Override
        public void onFail() {
            handler.sendEmptyMessage(0);
        }

        @Override
        public void onSuccess() {
            handler.sendEmptyMessage(1);
        }
    };
    private IOkHttp okHttp=new OkHttpImp();
    private IOkHttp.IHttpCallback callback=new IOkHttp.IHttpCallback() {
        @Override
        public void onResponse(Msg msg, int index) {
            dialog.dismiss();
            String response=msg.content();
            RS rs= (RS) Config.decry(response,RS.class);
            switch (rs.getRs()){
                case 1:
                    Toast.makeText(PersonalSetting.this,"修改成功",Toast.LENGTH_SHORT).show();
                    dealwithUploadInfoSuccess(index);
                    break;
                case -1:
                    Toast.makeText(PersonalSetting.this,"非法访问",Toast.LENGTH_SHORT).show();
                    break;
                case -2:
                    Toast.makeText(PersonalSetting.this,"修改失败",Toast.LENGTH_SHORT).show();
                    break;
            }
        }

        @Override
        public void onError(Exception e) {
            dialog.dismiss();
            Toast.makeText(PersonalSetting.this,"网络出错",Toast.LENGTH_SHORT).show();
        }
    };

    private void dealwithUploadInfoSuccess(int index) {
        UserDao userDao=BaseApplication.getDaoSession().getUserDao();
        switch(index){
            case 0://处理名字更新
                tv_name.setText(temp_name);
                user.setRealName(temp_name);//更新视图
                userDao.update(user); //更新数据库

                //广播更新名字
                Intent intent=new Intent(TYPE_NAME);
                intent.putExtra("name",temp_name);
                sendBroadcast(intent);
                break;
            case 1: //更新性别
                tv_sex.setText(temp_sex);
                user.setSex(temp_sex.equals("男")?1:2);
                userDao.update(user);
                break;
            case 2:  //更新职业
                tv_job.setText(temp_job);
                user.setProfessional(temp_job);
                userDao.update(user);
                break;
        }
    }

    @Override
    protected void findId() {
        toolbar= (Toolbar) findViewById(R.id.toolbar);
        rl_head= (RelativeLayout) findViewById(R.id.setting_rl_head);
        ci_head= (CircleImageView) findViewById(R.id.personsetting_iv_head);
        rl_name= (RelativeLayout) findViewById(R.id.setting_rl_name);
        tv_name= (TextView) findViewById(R.id.personsetting_et_name);
        tv_phone= (TextView) findViewById(R.id.personsetting_et_phone);
        rl_sex= (RelativeLayout) findViewById(R.id.setting_rl_sex);
        tv_sex= (TextView) findViewById(R.id.personsetting_et_sex);
        rl_age= (RelativeLayout) findViewById(R.id.setting_rl_age);
        tv_age= (TextView) findViewById(R.id.personsetting_et_age);
        rl_job= (RelativeLayout) findViewById(R.id.setting_rl_job);
        tv_job= (TextView) findViewById(R.id.personsetting_et_job);
        rl_insure= (RelativeLayout) findViewById(R.id.setting_rl_insure);
        tv_owner= (TextView) findViewById(R.id.personsetting_tv_owner);
    }

    @Override
    protected void logic() {
        //获取用户资料
        UserDao userDao= BaseApplication.getDaoSession().getUserDao();
        List list=userDao.queryBuilder().list();
        user= (User) list.get(0);

        //toolbar设置
        toolbar.setTitle("个人设置");
        toolbar.setNavigationIcon(R.mipmap.back_arrow_black);
        setSupportActionBar(toolbar);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        //progressdialog设置
        dialog=new ProgressDialog(this);

        //姓名设置
        rl_name.setOnClickListener(this);
        tv_name.setText(user.getRealName());

        //手机号码设置
        tv_phone.setText(user.getUserPhone());

        //设置性别
        rl_sex.setOnClickListener(this);
        Log.d("xx","sex:::"+user.getSex());
        tv_sex.setText(user.getSex().equals(1)?"男":"女");

        //设置年龄
        tv_age.setText(user.getAge());

        //设置职业
        rl_job.setOnClickListener(this);
        tv_job.setText(user.getProfessional());

        //设置车主认证
        rl_insure.setClickable(false);
        HashMap<String,String> hashMap=new HashMap<>();
        hashMap.put("UserPhone",user.getUserPhone());
        hashMap.put("UserPassword",user.getUserPwd());
        okHttp.httpInfoPost(Config.URL + Config.USERIDENTITYAUTH, Config.translateMap(hashMap), new IOkHttp.IHttpCallback() {
            @Override
            public void onResponse(Msg msg, int index) {
                String message=msg.content();
                RSIdentity rsIdentity= (RSIdentity) Config.decry(message,RSIdentity.class);
                if(rsIdentity.getRS()!=1){
                    return;
                }
                dealwithIdentity(rsIdentity);
            }

            @Override
            public void onError(Exception e) {

            }
        });

        //头像设置
        rl_head.setOnClickListener(this);
        Glide.with(this)
                .load(new File(Config.HEADLOCATION))
                .asBitmap()
                .diskCacheStrategy(DiskCacheStrategy.NONE)
                .skipMemoryCache(true)
                .into(new SimpleTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                        ci_head.setBitmap(resource);
                    }
                });

    }

    private void dealwithIdentity(RSIdentity rsIdentity) {
        if(rsIdentity==null){
            return;
        }
        //认证信息
        if(rsIdentity.getAudit()==1){
            rl_insure.setClickable(true);
            rl_insure.setOnClickListener(PersonalSetting.this);
            tv_owner.setTextColor(Color.RED);
            tv_owner.setText("未认证");
        }else{
            tv_owner.setTextColor(Color.GREEN);
            tv_owner.setText("已认证");
            rl_insure.setClickable(false);
        }
        //认证照片和身份证
        url_back=rsIdentity.getCardReverse();
        url_front=rsIdentity.getCardPositive();
        num_identity=rsIdentity.getIDCard();
    }

    private void broadToMain(String typeHead) {
        Intent intent = null;
        switch (typeHead){
            case TYPE_HEAD:
                intent=new Intent(TYPE_HEAD);
                break;
            case TYPE_NAME:
                intent=new Intent(TYPE_NAME);
                break;
        }
        sendBroadcast(intent);
    }

    @Override
    protected int setLayout() {
        return R.layout.activity_setting;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.setting_rl_head:  //设置头像栏点击
                dealWithHead();
                break;
            case R.id.setting_rl_name:  //姓名
                new MaterialDialog.Builder(this)
                        .title("输入姓名")
                        .inputType(InputType.TYPE_CLASS_TEXT)
                        .input("姓名", tv_name.getText().toString(), false, new MaterialDialog.InputCallback() {
                            @Override
                            public void onInput(@NonNull MaterialDialog dialog, CharSequence input) {
                                temp_name=input.toString();
                                HashMap<String,String> hashMap=new HashMap<String, String>();
                                hashMap.put("RealName",input.toString());
                                hashMap.put("Sex",user.getSex()+"");
                                hashMap.put("Professional",user.getProfessional());
                                dealwithInfo(hashMap,0);

                            }
                        }).show();
                break;
            case R.id.setting_rl_sex:  //性别
                new  MaterialDialog.Builder(this)
                        .title("选择性别")
                        .items(R.array.sex)
                        .itemsCallback(new MaterialDialog.ListCallback() {
                            @Override
                            public void onSelection(MaterialDialog dialog, View itemView, int which, CharSequence text) {
                                temp_sex=text.toString();
                                HashMap<String,String> hashMap=new HashMap<String, String>();
                                hashMap.put("RealName",user.getRealName());
                                hashMap.put("Sex",text.toString().equals("男")?"1":"2");
                                hashMap.put("Professional",user.getProfessional());
                                dealwithInfo(hashMap,1);
                            }
                        }).show();
                break;
            case R.id.setting_rl_insure:  //年龄
                openActivity(InsureActivity.class);
                break;
            case R.id.setting_rl_job:  //职业
                new MaterialDialog.Builder(this)
                        .title("输入职业")
                        .inputType(InputType.TYPE_CLASS_TEXT)
                        .input("职业", tv_job.getText().toString(), false, new MaterialDialog.InputCallback() {
                            @Override
                            public void onInput(@NonNull MaterialDialog dialog, CharSequence input) {
                                temp_job=input.toString();
                                HashMap<String,String> hashMap=new HashMap<String, String>();
                                hashMap.put("RealName",user.getRealName());
                                hashMap.put("Sex",user.getSex()+"");
                                hashMap.put("Professional",input.toString());
                                dealwithInfo(hashMap,2);
                            }
                        }).show();
                break;
        }
    }

    private void dealwithInfo(HashMap<String, String> hashMap, int index) {
        dialog.setMessage("正在更新");
        dialog.show();
        hashMap.put("UserPhone",user.getUserPhone());
        hashMap.put("UserPassword",user.getUserPwd());
        okHttp.httpInfoPost(Config.URL+Config.MODIFYUSERINFO,Config.translateMap(hashMap),callback,index);
    }

    private void dealWithHead() {
        new MaterialDialog.Builder(this)
                .title("设置头像")
                .items(R.array.pickHead)
                .itemsCallback(new MaterialDialog.ListCallback() {
                    @Override
                    public void onSelection(MaterialDialog dialog, View itemView, int which, CharSequence text) {
                        switch (which){
                            case 0://相机拍摄
                                capture();
                                break;
                            case 1://相册选取
                                album();
                                break;
                        }
                    }
                }).show();
    }

    //相机拍摄处理
    private void album() {
        Intent intent=new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");
        if(intent.resolveActivity(getPackageManager())!=null){
            startActivityForResult(intent,GALLERY_IAMGE);
        }
    }

    //相册选取照片处理
    private void capture() {
        Intent intent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if(intent.resolveActivity(getPackageManager())!=null){
            File file=createFile();
            if(file!=null){
                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
                startActivityForResult(intent,CAPTURE_IMAGE);
            }
        }else{
            Toast.makeText(this,"无法启动相机",Toast.LENGTH_SHORT).show();
        }
    }

    private String mCurrentPath;
    private File createFile() {
        File file=new File(getExternalCacheDir(),"head.jpeg");
        mCurrentPath=file.getAbsolutePath();
        return file;
    }
    private String mFilePath;
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(resultCode==RESULT_OK){
            String filePath=null;
            if(requestCode==CAPTURE_IMAGE){
                if(mCurrentPath!=null){
                    filePath=mCurrentPath;
                }
            }else if(requestCode==GALLERY_IAMGE){
                filePath=getPath(data.getData());
            }
            if(!TextUtils.isEmpty(filePath)){
                mFilePath=filePath;
                dialog.setMessage("正在上传头像");
                dialog.show();
                new Thread(){
                    @Override
                    public void run() {
                        HashMap<String,String> hashMap=new HashMap();
                        hashMap.put("UserPhone",user.getUserPhone());
                        hashMap.put("UserPassword",user.getUserPwd());
                        FileUtils.saveBitmap(Config.HEADLOCATION,BitmapFactory.decodeFile(mFilePath));
                        FileImageUpload.uploadFile(new File(mFilePath), "Head", Config.translateMap(hashMap), Config.URL + Config.MODIFYUSERHEAD, imageCallback); //上传头像
                    }
                }.start();
            }
        }
    }

    //处理上传成功的后续
    private void dealwithUploadSuccess() {
        dialog.dismiss();

        Toast.makeText(this,"上传成功",Toast.LENGTH_SHORT).show();
            //设置头像
        Glide.with(this)
                    .load(mFilePath)
                    .asBitmap()
                    .into(new ViewTarget<CircleImageView,Bitmap>(ci_head) {
                        @Override
                        public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                            ci_head.setBitmap(resource);
                        }
                    });

            //广播通知主界面修改头像
            broadToMain(TYPE_HEAD);
    }

    private String getPath(Uri data) {
        String filePath=null;
        String[] ff=new String[]{MediaStore.MediaColumns.DATA};
        Cursor cursor=getContentResolver().query(data,ff,null,null,null);
        if(cursor==null){
            return null;
        }
        cursor.moveToFirst();
        filePath=cursor.getString(cursor.getColumnIndex(ff[0]));
        cursor.close();
        return filePath;
    }
}
